package com.heroCW.bodhiAttic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heroCW.bodhiAttic.entity.User;
import com.heroCW.bodhiAttic.mapper.UserMapper;
import com.heroCW.bodhiAttic.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public User getOneByPhone(String phone) {
        // 比对成功，则登录成功
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getPhone, phone);

        return this.getOne(lambdaQueryWrapper);
    }

    @Override
    @Transactional
    public User saveUser(String phone) {

        User user = new User();

        StringBuilder builder = new StringBuilder("user-");
        String substring = phone.substring(phone.length()-4);

        user.setName(builder.append(substring).toString());
        user.setPhone(phone);
        user.setStatus(1);

        this.save(user);

        return user;
    }

    @Override
    public IPage<User> getPage(int page, int pageSize, String name) {
        // 构造条件构造器
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        // 添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name), User::getName, name);

        //构造分页构造器
        IPage<User> pageInfo = new Page<>(page, pageSize);

        return this.page(pageInfo, queryWrapper);
    }
}
